package com.syl.upimg.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.syl.upimg.bean.BaseBean;
import com.syl.upimg.enums.ImageUploadTypeEnum;
import com.syl.upimg.service.BaseUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Iterator;

/**
 * 网易严选羊毛
 *
 * @author syl
 * @create 2019-08-02 14:55
 **/
@Service
public class NetEaseFleece implements BaseUpload {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public RestTemplate createRestTemplate() {
        return restTemplate;
    }

    @Override
    public String[] getLimit() {
        return new String[]{"jpg", "png", "gif"};
    }

    @Override
    public String getUrl() {
        return "http://you.163.com/xhr/file/upload.json";
    }

    @Override
    public HttpHeaders getDefaultHeader() {
        return getDefaultHeader("http://you.163.com", "http://you.163.com");
    }

    @Override
    public LinkedMultiValueMap<String, Object> getParam(FileSystemResource file, String fileName, String fileType) {
        LinkedMultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("file", file);
        multiValueMap.add("format", "json");
        return multiValueMap;
    }

    public BaseBean upload(String filePath) throws IOException {
        return this.upload(filePath, false);
    }

    /**
     * 上传图片
     * @param filePath
     *
     * @return 直接返回图片url
     * @throws IOException
     */
    public BaseBean upload(String filePath, boolean delete) throws IOException {
        long startTime = System.currentTimeMillis();
        String upload = this.uploadByString(filePath, delete);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(upload);
        String code = jsonNode.get("code").asText();
        if (StringUtils.isEmpty(code)) return null;
        JsonNode data = jsonNode.get("data");
        String result = null;
        Iterator<JsonNode> elements = data.elements();
        while (elements.hasNext()) {
            JsonNode next = elements.next();
            if (next == null) continue;
            result = next.asText();
        }
        long endTime = System.currentTimeMillis();
        int intValue = new Long(endTime - startTime).intValue();
        return new BaseBean().setBaseUrl(result).setTimerMs(intValue).setImageUploadTypeEnum(ImageUploadTypeEnum.NET_EASE);
    }

}
